package com.example.demo.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import com.example.demo.AutoRealTimeMonitoring;
import com.example.demo.LogUtil;
import com.example.demo.service.AdjudeMethod;
import com.example.demo.service.MonitoringMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.normalClasses.eye.monitor_res_obj;

import freemarker.template.Template;

@Service
@Slf4j
public class MonitoringService implements MonitoringMethod, AdjudeMethod {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private FreeMarkerConfigurer freemarker;

    @Override
    public void Handle_abnormal_behavior(String msgString, String Template) {
        // TODO Auto-generated method stub
        List managers = (List) jdbcTemplate.queryForList("select email from t_people_right_static where `admin` = 9");
        String[] emailStrings = new String[managers.size()];
        //拿到所有管理员邮箱
        for (int i = 0; i < managers.size(); i++) {
            Map manager = (Map) managers.get(i);
            emailStrings[i] = (String) manager.get("email");
        }
        //生成内容
        for (int i = 0; i < emailStrings.length; i++) {
            MimeMessage msg = mailSender.createMimeMessage();
            try {
                MimeMessageHelper helper = new MimeMessageHelper(msg, true);
                //静态赋值，不可更改
                helper.setFrom("1987477513@qq.com");
                helper.setTo(emailStrings[i]);
                helper.setSubject("新的信息");
                //封装模板使用的数据
                Map<String, Object> modeMap = new HashMap<>();
                modeMap.put("maintext", msgString);
                //得到模板信息
                Template template = freemarker.getConfiguration().getTemplate(Template);
                //转化字符串
                String htmlString = FreeMarkerTemplateUtils.processTemplateIntoString(template, modeMap);
                helper.setText(htmlString, true);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                log.warn(LogUtil.logSpec("Auto_send_mail has Exception"));
            }
            mailSender.send(msg);
            log.info(LogUtil.logSpec("send to " + emailStrings[i] + "a handle email"));
        }
    }


    @Override
    public void change_adjude_obj(String username, String adjude_obj, String arbitration, String id) {
        // TODO Auto-generated method stub
        //超前判断裁决结果，直接触发邮箱提示，告诉管理者最新的裁决结果
        List admin = (List) jdbcTemplate.queryForList("select * from t_illegal_judge where `id` ='" + id + "'");
        if (admin.size() > 0) {
            Map res_adj = (Map) admin.get(0);
            int res = getAdmin_agreenum(res_adj);
            //为当前裁决int
            int now_adj_res = 0;
            if (arbitration.equals("true")) {
                now_adj_res = 1;
                jdbcTemplate.update("UPDATE t_illegal_judge set `" + getAdmin_string(username) + "`='true' where `id` ='" + id + "'");
            }
            //条件触动,触动
            if (now_adj_res + res == 3 && now_adj_res == 1) {
                this.Handle_abnormal_behavior("对 " + adjude_obj + "的用户行为，异常代码为" + res_adj.get("illegal_type") + "。 做出了禁止此用户行为。", "template2.html");
                jdbcTemplate.update("UPDATE t_illegal_judge_res set `status`='true' where `id` ='" + id + "'");//对裁决条进行状态更新
                return;
            }
        } else {
            log.error(LogUtil.logSpec("change_adjude_obj has problem, system mabye has bug", 8));
        }
    }


    //应对于数据库中列表与数据库毫不关联的
    public static String getAdmin_string(String username) {
        switch (username) {
            case "0p11p92p8":
                return "ruo";
            case "0p81p9":
                return "luo";
            case "0p31p62p9":
                return "wang";
            case "0p51p22p3":
                return "ma";
            case "0p21p32p4":
                return "chen";
            case "0p31p92p13p2":
                return "liu";
            case "0p11p6":
                return "li";
            case "0p11p5":
                return "guo";
            default:
                break;
        }
        return null;
    }

    //判断此条裁决几人同意
    public static int getAdmin_agreenum(Map result) {
        int i = 0;
        //依次提取依次比较
        String ruo = (String) result.get("ruo");
        String luo = (String) result.get("luo");
        String wang = (String) result.get("wang");
        String ma = (String) result.get("ma");
        String chen = (String) result.get("chen");
        String liu = (String) result.get("liu");
        String li = (String) result.get("li");
        String guo = (String) result.get("guo");
        if (ruo.equals("true")) {
            i++;
        }
        if (luo.equals("true")) {
            i++;
        }
        if (wang.equals("true")) {
            i++;
        }
        if (ma.equals("true")) {
            i++;
        }
        if (chen.equals("true")) {
            i++;
        }
        if (liu.equals("true")) {
            i++;
        }
        if (li.equals("true")) {
            i++;
        }
        if (guo.equals("true")) {
            i++;
        }
        return i;
    }

    @Override
    public void Send_abnormal_behavior(String msgString, String Template, String username) {
        // TODO Auto-generated method stub
        String usernameString = username;
        String mailString = "";
        List user = (List) jdbcTemplate.queryForList("select email from t_people_right_static where `username` ='" + usernameString + "'");
        if (user.size() > 0) {
            Map people = (Map) user.get(0);
            mailString = (String) people.get("email");
        }
        MimeMessage msg = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(msg, true);
            //静态赋值，不可更改
            helper.setFrom("1987477513@qq.com");
            helper.setTo(mailString);
            helper.setSubject("新的信息");
            //封装模板使用的数据
            Map<String, Object> modeMap = new HashMap<>();
            modeMap.put("maintext", msgString);
            //得到模板信息
            Template template = freemarker.getConfiguration().getTemplate(Template);
            //转化字符串
            String htmlString = FreeMarkerTemplateUtils.processTemplateIntoString(template, modeMap);
            helper.setText(htmlString, true);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            log.warn(LogUtil.logSpec("Send_abnormal_behavior has Exception"));
        }
        mailSender.send(msg);
        log.info(LogUtil.logSpec("send to " + mailString + "a abnormal_notice email"));
    }

    @Override
    public void Make_adjude_behavior(String username, int type, String mesg) {
        // TODO Auto-generated method stub
        //获取编号
        List user = (List) jdbcTemplate.queryForList("SELECT COUNT(*) FROM `t_illegal_judge`");
        int id = Integer.parseInt(String.valueOf((long) ((Map) user.get(0)).get("count(*)")));
        //插入新的裁决条
        jdbcTemplate.update("INSERT INTO `t_illegal_judge`(`username`,`id`,`illegal_type`,`ruo`,`luo`,`wang`,`ma`,`chen`,`liu`,`li`,`guo`) VALUES (?,?,?,?,?,?,?,?,?,?,?)", username, id, type, "false", "false", "false", "false", "false", "false", "false", "false");
        jdbcTemplate.update("INSERT INTO `t_illegal_judge_res`(`id`,`status`) VALUES (?,?)", id, "false");
        //为处理队列新加入一条
        monitor_res_obj msg = new monitor_res_obj(username, type, id);
        //将备注信息加入主体
        if (!mesg.equals("")) {
            msg.appendMessage(mesg);
        }
        try {
            AutoRealTimeMonitoring.monitoring_message.push(msg);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error(LogUtil.logSpec("Make_adjude_behavior has push problem"));
        }
    }
}
